package com.ywjh.inter.servlet;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywjh.inter.common.SystemConfig;

import net.sf.json.JSONObject;

public class FileUpload extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8007994037363518760L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter pw = resp.getWriter();
		DataInputStream in = new DataInputStream(request.getInputStream());
		String uploadPath = "/mnt";
		String fileName = "/upload/" + System.currentTimeMillis() + ".jpg";

		RandomAccessFile file = new RandomAccessFile(uploadPath + fileName, "rw");
		int length = 0;
		byte[] buffer = new byte[1024];
		while ((length = in.read(buffer)) > -1) {
			file.write(buffer, 0, length);
		}
		in.close();
		file.close();
		JSONObject o = new JSONObject();
		int r = 1;
		String e = "";
		r = 1;
		e = "";
		JSONObject d = new JSONObject();
		d.put("domain", SystemConfig.SERVER_DOMAIN);
		d.put("file", fileName);
		o.put("d", d);
		o.put("r", r);
		o.put("e", e);

		pw.write(o.toString());

		pw.flush();
		pw.close();
	}
}
